﻿// <copyright file="CompositionInitializerEx.cs" company="Microsoft Corporation">
// Copyright (c) 2009 Microsoft Corporation All Rights Reserved
// </copyright>
// <author>Michael S. Scherotter</author>
// <email>mischero@microsoft.com</email>
// <date>2010-08-27</date>
// <summary>Composition Initializer that optionally allows recomposition </summary>
 
namespace Microsoft.WebAnalytics
{
    using System;
    using System.ComponentModel.Composition;
    using System.ComponentModel.Composition.Hosting;
    using System.ComponentModel.Composition.Primitives;

    /// <summary>
    /// Composition initializer that optionally allows re-composition
    /// </summary>
    public static class CompositionInitializerEx
    {
        /// <summary>
        /// Satisfy imports
        /// </summary>
        /// <param name="part">the compose-able part</param>
        /// <param name="allowRecomposition">allow re-composition (default is false)</param>
        /// <remarks>If CompositionHostEx.Initialize() has not been previously called, 
        /// the allow Re-composition parameter will be ignored and CompositionInitializer.SatisfyImports(part)
        /// will be called.</remarks>
        public static void SatisfyImports(ComposablePart part, bool allowRecomposition = false)
        {
            if (!Hosting.CompositionHostEx.IsInitialized)
            {
                CompositionInitializer.SatisfyImports(part);

                return;
            }

            var container = Hosting.CompositionHostEx.GetContainer();

            if (allowRecomposition)
            {
                CompositionInitializer.SatisfyImports(part);
            }
            else
            {
                container.SatisfyImportsOnce(part);
            }
        }
 
        /// <summary>
        /// Satisfy Imports
        /// </summary>
        /// <param name="attributedPart">the attributed part</param>
        /// <param name="allowRecomposition">allow re-composition (default is false)</param>
        /// <remarks>If CompositionHostEx.Initialize() has not been previously called, 
        /// the allow Re composition parameter will be ignored and CompositionInitializer.SatisfyImports(part)
        /// will be called.</remarks>
        public static void SatisfyImports(object attributedPart, bool allowRecomposition = false)
        {
            if (!Hosting.CompositionHostEx.IsInitialized)
            {
                CompositionInitializer.SatisfyImports(attributedPart);

                return;
            }

            var container = Hosting.CompositionHostEx.GetContainer();

            if (allowRecomposition)
            {
                CompositionInitializer.SatisfyImports(attributedPart);
            }
            else
            {
                container.SatisfyImportsOnce(attributedPart);
            }
        }
    }
}
